from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from mystu.models import Student
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage, InvalidPage


# 接收POST请求数据
def addStu(request):
    stu = None
    msg = ""
    if request.POST:
        name = request.POST['name']
        gender = request.POST['gender']
        birthday = request.POST['birthday']
        major = request.POST['major']
        stu = Student(name=name, gender=gender, birthday=birthday, major=major)
        stu.save()
        msg = name + "添加成功！"

    return listByPage(request, msg)


def delStu(request):
    stu = None
    msg = ""
    if request.GET:
        n = request.GET['id']
        n = int(n)
        Student.objects.filter(id=n).delete()
        msg = "学号为" + str(n) + "的学生删除成功！"
    return listByPage(request, msg)


def updateStu(request):
    stu = None
    msg = ""
    if request.POST:
        id = request.POST['id']
        name = request.POST['name']
        gender = request.POST['gender']
        birthday = request.POST['birthday']
        major = request.POST['major']

        stu = Student.objects.filter(id=int(id)).update(name=name, gender=gender, birthday=birthday, major=major)

        msg = "学号为" + id + "的学生更新数据成功！"

    return listByPage(request, msg)


def query(request, msg=""):
    list = Student.objects.all()
    return render(request, "admin/school.html", {"stus": list, "msg": msg})

@login_required
def listByPage(request, msg=""):
    stus = Student.objects.order_by("-id")
    paginator = Paginator(stus, 3)

    page = request.GET.get('pageNum')
    try:
        stus = paginator.page(page)
    except PageNotAnInteger:
        stus = paginator.page(1)
    except InvalidPage:
        # 如果请求的页数不存在, 重定向页面
        msg = '找不到页面的内容'
    except EmptyPage:
        # 如果请求的页数不在合法的页数范围内，返回结果的最后一页。
        stus = paginator.page(paginator.num_pages)


    print("page", stus)
    return render(request, "admin/school.html", {"stus": stus, "msg": msg})
